﻿# -*- coding: utf-8 -*-
import sys  
reload(sys)
sys.setdefaultencoding('utf8')  
import string
import cgi
import urllib
import datetime
import random
import re

from django.utils import simplejson as json
from sgmllib import SGMLParser, SGMLParseError
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from tweepy import *
import datastore_cache
datastore_cache.DatastoreCachingShim.Install()

consumer_key = "c99OpyISaGpmt3zbUpVvQ"
consumer_secret = "64jP2YW6MkWuMPNnWQXs9qh5DMc5YeIIybG5I02hI"
oauth_token = " "
oauth_verifier = " "

StartUrl = "/API/"
SearchUrl = "/API/search.json"
TwitterUrl = "https://api.twitter.com/1/"
TwitterSearchUrl = "http://search.twitter.com/"

DMGetStartUrl = "/API/direct_messages"
DMGetSentUrl = "/API/direct_messages/sent"
DMGetSpecifiedUrl = "/API/direct_messages/"

TweetsUpdateUrl = "/statuses/update"
RetweetUrl = "/statuses/retweet/"
DelTweetUrl = "/statuses/destroy/"
PostDMUrl = "/direct_messages/new"
DelDMUrl = "/direct_messages/destroy/"
FriendCreateUrl = "/friendships/create"
FriendDelUrl = "/friendships/destroy"
FriendUpdateUrl = "/friendships/update"
FavCreateUrl = "/favorites/create/"
FavDelUrl = "/favorites/destroy/"
ListMemberDelUrl = "/lists/members/destroy"
ListMemberAddUrl = "/lists/members/create"
ListDelUrl = "/lists/destroy"
ListCreateUrl = "/lists/create"
ListUpdateUrl = "/lists/update"
ListSubCreate = "/lists/subscribers/create"
ListSubDel = "/lists/subscribers/destroy"
SearchCreateUrl = "/saved_searches/create"
SearchDelUrl = "/saved_searches/destroy/"

class UserToken(db.Model):
	username = db.StringProperty(required=True)
	usernumber = db.StringProperty(required=True)
	oauth_token = db.StringProperty(required=True)
	oauth_verifier = db.StringProperty(required=True)
	access_token_key = db.StringProperty(required=True)
	access_token_secret = db.StringProperty(required=True)
	consumer_key = db.StringProperty(required=False)
	consumer_secret = db.StringProperty(required=False)
	createdtime = db.DateTimeProperty(required=True, auto_now_add=True)

class LastTweet(db.Model):
	username = db.StringProperty(required=False)
	tweetid = db.IntegerProperty(required=True)
	lastuserid = db.StringProperty(required=True)

class ChnBot(webapp.RequestHandler):
	def __init__(self):
		self.apikey = consumer_key
		self.apisecret = consumer_secret
		self.try_error = False
		self.try_times = 5
	def get(self, callurl):
		usernum = '166892821'
		UserObjGQL = UserToken.gql("WHERE usernumber = :1", usernum)
		UserObj = UserObjGQL.get()
		TweetObjGQL = LastTweet.gql("WHERE lastuserid = :1", usernum)
		TweetObj = TweetObjGQL.get()
		if UserObj != None:
			self.apikey = UserObj.consumer_key
			self.apisecret = UserObj.consumer_secret
			auth = OAuthHandler(self.apikey, self.apisecret)
			auth.set_access_token(UserObj.access_token_key.decode("utf-8"), UserObj.access_token_secret.decode("utf-8"))
			api = API(auth, 'api.twitter.com', 'search.twitter.com', None, True)
		else:
			self.response.out.write("User:"+ usernum + "Not Oauth yet!<br />")
			return
		if TweetObj != None:
			try:
				(s,statuscontent) = api.search(q = '了', rpp = 60, page = 1, lang = 'zh', since_id = TweetObj.tweetid, include_entities = 't')
			except:
				self.response.out.write(TweepError)
				return
			tweets = json.loads(statuscontent)
			TweetObj.tweetid = tweets["max_id"]
			(s,lateststatus) = api.get_status(tweets["max_id"])
			latesttweet = json.loads(lateststatus)
			TweetObj.username = latesttweet["user"]["screen_name"]
			TweetObj.put()
		else:
			try:
				(s,statuscontent) = api.search(q = '了', rpp = 40, page = 1, lang = 'zh', include_entities = 't')
			except:
				self.response.out.write(TweepError)
				return
			tweets = json.loads(statuscontent)
			(s,lateststatus) = api.get_status(tweets["max_id"])
			latesttweet = json.loads(lateststatus)
			TweetObj = LastTweet(username = latesttweet["user"]["screen_name"], tweetid = tweets["max_id"], lastuserid = usernum)
			TweetObj.put()
		for val in tweets['results']:
			if val["from_user_id"] == usernum:
				continue
			TweetObjGQL = LastTweet.gql("WHERE lastuserid = :1", val["from_user_id_str"])
			TweetObj = TweetObjGQL.get()
			if TweetObj == None:
				#self.response.out.write('<1>'+val["from_user"]+'<br />')
				try:
					(s,statuscontent) = api.user_timeline(user_id = val["from_user_id"], count = 12, include_rts = 't')
				except:
					statuscontent = None
					#self.response.out.write(TweepError)
					self.response.out.write('<User '+val["from_user"]+' Not Found<br />')
					pass
				if statuscontent != None:
					usertweets = json.loads(statuscontent)
					chntweetnum = 0
					spam = 0
					for val2 in usertweets:
						len1 = len(unicode(val2["text"].decode('utf-8')))
						len2 = len(re.sub(ur"[\u4e00-\u9fa5]",'aa',val2["text"]))
						chnnum = len2 - len1
						if chnnum > (len1/3) or chnnum > 7:
							chntweetnum += 1
						if val2["text"].startswith('@wenyunchao'):
							spam +=1
						#self.response.out.write(val2["text"]+'<br />'+str(chnnum)+" "+str(chntweetnum)+'<br />')
					if spam > 4:
						try:
							(s,resps) = api.destroy_friendship(None, None, screen_name = val["from_user"])
						except:
							self.response.out.write(TweepError)
							pass
						continue
					if chntweetnum > 4:
						create_friendship = True
						# try:
							# (s,resps) = api.create_friendship(None, None, screen_name = val["from_user"], follow = 'true')
						# except:
							# create_friendship = False
							# self.response.out.write(TweepError)
							# pass
						if create_friendship == True:
							self.response.out.write('following '+ val["from_user"] + ' 1<br />')
							TweetObj = LastTweet(username = val["from_user"], tweetid = 0, lastuserid = val["from_user_id_str"])
							TweetObj.put()
						else:
							self.response.out.write('following '+ val["from_user"] + 'failed 1<br />')
					else:
						self.response.out.write(val["from_user"]+str(chntweetnum)+"non chn user 1<br />")
			else:
				self.response.out.write(TweetObj.username + ' already followed<br />')
			for mentioneduser in val["entities"]["user_mentions"]:
				TweetObjGQL = LastTweet.gql("WHERE lastuserid = :1", mentioneduser["id_str"])
				TweetObj = TweetObjGQL.get()
				if TweetObj == None:
					#self.response.out.write('<2>'+mentioneduser["screen_name"]+'<br />')
					try:
						(s,statuscontent) = api.user_timeline(screen_name = mentioneduser["screen_name"], count = 12, include_rts = 't')
					except:
						self.response.out.write('<User '+mentioneduser["screen_name"]+' Not Found<br />')
						statuscontent = None
						pass
					if statuscontent != None:
						usertweets = json.loads(statuscontent)
						chntweetnum = 0
						for val2 in usertweets:
							len1 = len(unicode(val2["text"].decode('utf-8')))
							len2 = len(re.sub(ur"[\u4e00-\u9fa5]",'aa',val2["text"]))
							chnnum = len2 - len1
							if chnnum > len1/3 or chnnum > 7:
								chntweetnum += 1
							#self.response.out.write(val2["text"]+'<br />'+str(chnnum)+" "+str(chntweetnum)+'<br />')
						if chntweetnum > 4:
							create_friendship = True
							# try:
								# (s,resps) = api.create_friendship(None, userid = mentioneduser["id_str"], screen_name = mentioneduser["screen_name"], follow = 'true')
							# except:
								# create_friendship = False
								# self.response.out.write(TweepError)
								# pass
							if create_friendship == True:
								self.response.out.write('following '+ mentioneduser["screen_name"] + ' 2<br />')
								TweetObj = LastTweet(username = mentioneduser["screen_name"], tweetid = 0, lastuserid = mentioneduser["id_str"])
								TweetObj.put()
							else:
								self.response.out.write('following '+ val["from_user"] + 'failed 2<br />')
						else:
							self.response.out.write(mentioneduser["screen_name"]+str(chntweetnum)+"non chn user 2<br />")
				else:
					self.response.out.write(TweetObj.username + ' already followed<br />')
			#self.response.out.write("<br />")
			#self.response.out.write(val["entities"]["user_mentions"])
			#self.response.out.write("<br />")
			#self.response.out.write("<br />")
		return

application = webapp.WSGIApplication(
																		 [(r'/chnbot(.*)', ChnBot)],
																		 debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()